package com.rytong.tools.ui.chart;

import java.util.ArrayList;
import java.util.List;

import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.CssStyle;
import com.rytong.tools.ui.LPLayout;
import com.rytong.tools.ui.LPScrollView;
import com.rytong.tools.ui.LPLayout.MyLPLayout;
import com.rytong.tools.utils.Utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.view.MotionEvent;
import android.widget.AbsoluteLayout;

/**
 * @author lixiao 折线图控件
 */
@SuppressWarnings("deprecation")
public class LPLinePlotLayout extends Component implements Chart {

    // 折线的宽
    int lineWidth_;
    // 折线的颜色
    int lineColor_;
    // 点的颜色集合
    ArrayList<Integer> pointColor_;
    // 点的半径集合
    ArrayList<Integer> pointRadius_;
    // 点的value集合
    ArrayList<String> pointValues_;

    // 渐变色属性
    int gradientType_;
    int startColorStr_;
    int endColorStr_;
    float alpha_;

    // x轴的marginTop
    float xScaleMaginTop_;
    // y轴的marginTop
    float yScaleMaginTop_;
    // y轴的刻度值集合
    List<String> yValueSpace_;

    // 渐变属性
    LinearGradient mLinearGradient_;
    // 有无点的折线图
    boolean hasPoint_;

    // 设置折线画笔
    Paint linePaint_ = new Paint();
    
    //得到折点的最高值
    float maxHeight_;
    
    public class MyLPLinePlotLayout extends AbsoluteLayout implements CompositedComponent {

        public MyLPLinePlotLayout(Context context, String value) {
            super(context);
            this.setWillNotDraw(false);
        }

        @Override
        public Component composited() {
            return LPLinePlotLayout.this;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            drawLinePlot(canvas);
        }

        /**
         * 绘制折线图
         * 
         * @param canvas
         */
        private void drawLinePlot(Canvas canvas) {
            Path path = new Path();
            int startPointX = -1;
            int endPointX = -1;
            int size = childrenList_.size();
            if (alpha_ > 0)
                paint_.setAlpha((int) (alpha_ * 255));
            // 绘制折线下方渐变区域
            if (startColorStr_ != 0 || endColorStr_ != 0) {
                // 设置渐变
                if (gradientType_ == 1) {// 水平渐变
                    mLinearGradient_ = new LinearGradient(childrenList_.get(0).left_, 0, childrenList_.get(size - 1).left_, 0, new int[] { startColorStr_, endColorStr_ },
                            null, Shader.TileMode.MIRROR);
                } else {
                    mLinearGradient_ = new LinearGradient(0, height_ - maxHeight_, 0, height_, new int[] { startColorStr_, endColorStr_ },
                            null, Shader.TileMode.MIRROR);
                }
                paint_.setShader(mLinearGradient_);
                for (int i = 0; i < size; i++) {
                    if (i == 0) {
                        startPointX = childrenList_.get(i).left_;
                        path.moveTo(startPointX, height_);
                    }
                    path.lineTo(childrenList_.get(i).left_, height_ - childrenList_.get(i).top_);
                    if (i == size - 1) {
                        endPointX = childrenList_.get(i).left_;
                        path.lineTo(endPointX, height_);
                    }
                }
                canvas.drawPath(path, paint_);
            }
            // 绘制折线
            for (int i = 0; i < size; i++) {
                if (i != 0) {
                    canvas.drawLine(childrenList_.get(i - 1).left_, height_ - childrenList_.get(i - 1).top_,
                            childrenList_.get(i).left_, height_ - childrenList_.get(i).top_, linePaint_);
                }
            }
            // 绘制折线上的点
            if (pointRadius_ != null && pointColor_ != null) {
                for (int i = 0; i < size; i++) {
                    if(!((LITag)(childrenList_.get(i))).needDrawPoint_)
                        continue;
                    paint_.setColor(pointColor_.get(i));
                    canvas.drawCircle(childrenList_.get(i).left_, height_ - childrenList_.get(i).top_, pointRadius_.get(i),
                            paint_);
                }
            }
        }


        @Override
        public boolean onTouchEvent(MotionEvent event) {
            boolean isAction = false;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            	// 按下tr时候变色。
            	trDownColor(tr_, llvSV_);
                xDown_ = event.getX();
                yDown_ = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
            	// 移动tr恢复颜色。
            	int offset = (int) Math.abs(yDown_ - event.getY());
            	if (offset > offset_) {
            		trMoveColor(tr_, llvSV_);
            	}
                moveY(yDown_, event.getY());
                break;
            case MotionEvent.ACTION_UP:
            	// 抬起tr恢复颜色。
            	trUpColor(tr_, llvSV_);
                float xDown_ = event.getX();
                float yDown_ = event.getY();
                int size = childrenList_.size();
                for (int i = 0; i < size; i++) {
                    if (childrenList_.get(i).left_ == xDown_ && childrenList_.get(i).top_ == yDown_) {
                        String onclick = (String) childrenList_.get(i).getPropertyByName("onclick");
                        if (onclick != null && !onclick.equals("")) {
                            // 执行点击事件
                            isAction = onClick(onclick);
                        }
                    }
                }
                break;
            default:
                isAction = super.onTouchEvent(event);
            }
            return isAction;
        }

    }

    @Override
    public void initRealView(Activity activity, String nodeValue) {
        super.initRealView(activity, nodeValue);
        realView_ = new MyLPLinePlotLayout(activity, nodeValue);
        childrenList_ = new ArrayList<Component>();
    }
    
    @Override
    public void mouldW() throws Exception {
        mouldChildList();
        // 设置参数
        android.widget.AbsoluteLayout.LayoutParams lp = new android.widget.AbsoluteLayout.LayoutParams(width_, height_,
                0, 0);
        setLayoutParams(lp);
        paint_ = new Paint();
        paint_.setAntiAlias(true);

        linePaint_.setAntiAlias(true);
        linePaint_.setColor(lineColor_);
        linePaint_.setStrokeWidth(lineWidth_);

        // 获取折线的线宽和颜色
        cssStyle_ = this.cssStyle();
        String color = (String) cssStyle_.getProperty(CssStyle.BACKGROUNDCOLOR);
        if (null != color && !color.equals("")) {
            lineColor_ = Utils.getColorValue(color);
        }
        String linewidth = (String) cssStyle_.getProperty(CssStyle.WIDTH);
        if (null != linewidth && !linewidth.equals("")) {
            lineWidth_ = Integer.parseInt(fixedPX(linewidth));
            lineWidth_ = Utils.getFontSize(lineWidth_);
        }

        // 获得颜色渐变相关属性
        gradientType_ = cssStyle_.gradientType;
        startColorStr_ = cssStyle_.startColorStr;
        endColorStr_ = cssStyle_.endColorStr;
        alpha_ = cssStyle_.alpha;
        
        if(yValueSpace_ == null || yValueSpace_.size() == 0)
            return;
        int valueSize = yValueSpace_.size();
        int size = childrenList_.size();
        pointColor_ = null;
        pointColor_ = new ArrayList<Integer>();
        pointRadius_ = null;
        pointRadius_ = new ArrayList<Integer>();
        pointValues_ = null;
        pointValues_ = new ArrayList<String>();
        CssStyle cs = null;
        for (int i = 0; i < size; i++) {
            cs = childrenList_.get(i).cssStyle();
            // 获取点的value值
            String pointValue = (String) childrenList_.get(i).getPropertyByName("value");
            if (null != pointValue && !pointValue.equals("")) {
                pointValues_.add(pointValue);
            }
            if (cs != null) {
                // 获取点的半径和颜色
                String pointColor = (String) cs.getProperty(CssStyle.BACKGROUNDCOLOR);
                if (null != pointColor && !pointColor.equals("")) {
                    pointColor_.add(Utils.getColorValue(pointColor));
                }
                //获得点的top
                String pointradius = (String) cs.getProperty(CssStyle.WIDTH);
                if (null != pointradius && !pointradius.equals("")) {
                    pointRadius_.add(Utils.getFontSize(Integer.parseInt(fixedPX(pointradius)) >> 1));
                }
                String pointTop = (String) cs.getProperty(CssStyle.TOP);
                if(pointTop == null || pointTop.equals("") ){
                    childrenList_.get(i).top_ = (int) ((valueSize - 1) * yScaleMaginTop_
                            * Float.parseFloat(pointValues_.get(i)) / (Float.parseFloat(yValueSpace_.get(0)) - Float
                            .parseFloat(yValueSpace_.get(valueSize - 1))));
                }
                //获得点的最高值
                maxHeight_ = Math.max(maxHeight_, childrenList_.get(i).top_);
                //获得点的left
                String pointLeft = (String) cs.getProperty(CssStyle.LEFT);
                if(pointLeft == null || pointLeft.equals("")){
                    childrenList_.get(i).left_ = (int) (xScaleMaginTop_ * (i + 0.5));
                }
            }
        }
    }

    @Override
    public void setXScaleMarginTop(float valueSpace) {
        xScaleMaginTop_ = valueSpace;
    }

    @Override
    public float getXScalemarginTop() {
        return xScaleMaginTop_;
    }

    @Override
    public void setYScaleMarginTop(float valueSpace) {
        yScaleMaginTop_ = valueSpace;
    }

    @Override
    public float getYScaleMarginTop() {
        return yScaleMaginTop_;
    }

    @Override
    public void setYScaleValues(List<String> values) {
        yValueSpace_ = values;
    }

    @Override
    public List<String> getYScaleVaues() {
        return yValueSpace_;
    }

    @Override
    public void setXScaleValues(List<String> values) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public List<String> getXScaleValue() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void releaseResource(Component component) {
    	super.releaseResource(component);
        if(pointColor_ != null){
        	pointColor_.clear();
        	pointColor_ = null;
        }
        if(pointRadius_ != null){
        	pointRadius_.clear();
        	pointRadius_ = null;
        }
        if(pointValues_ != null){
        	pointValues_.clear();
        	pointValues_ = null;
        }
    	if(yValueSpace_ != null){
    		yValueSpace_.clear();
    		yValueSpace_ = null;
    	}
    }
}
